// src/utils/http.js 中
import axios from "axios";
import { UniAdapter } from "uniapp-axios-adapter";

const request = axios.create({
  baseURL: "https://www.xinchengai.top:8080",
  timeout: 30000,
  adapter: UniAdapter,
});

request.interceptors.request.use((config) => {
  uni.showLoading({
    mask: true,
  });
  const userInfo = uni.getStorageSync("userInfo") || {};
  if (userInfo.openid) {
    config.headers["openID"] = userInfo.openid;
    // config.headers["openID"] = "o25B061QEL28x2KvT4yBP8_Vh_VE";
  }
  //带上token
  return config;
});

//@ts-ignore
request.interceptors.response.use((response) => {
  if (request.config?.responseType === "stream") {
    console.log(response);
    return response;
  }
  uni.hideLoading();
  // 统一处理响应,返回Promise以便链式调用
  const { data } = response;
  if (data.status === "success") {
    if (data && data.response) {
      return Promise.resolve(data.response);
    } else {
      return Promise.reject(data.response);
    }
  } else {
    uni.showToast({
      title: data.response || "失败",
      icon: "none",
    });
    return Promise.reject(response);
  }
});

export default request;
